<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;




class Score extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    // 录入成绩页面
    public function result_input()
    {
        $classData =  Db::table('courses_result')
            ->alias('a')
            ->join("class b", 'a.banjiid = b.id')
            ->field("a.*,b.class_name")
            ->where('a.kechengid', input('get.kechengid'))->select();
        $this->assign('classData', $classData);

        $currentClass =  Db::name('class')
            ->where('id', input('get.banjiid'))->find();
        $this->assign('nowClass', $currentClass);

        $kechengListData =  Db::name('kecheng')
            ->where('id', input('get.kechengid'))->find();
        $this->assign('kechengdata', $kechengListData);

        return $this->fetch();
    }

    public function get_result_input_list()
    {
        $map['a.schoolid'] = array('eq', 99);
        $map['a.classid']  = array('eq', input('get.banjiid'));
        $map['a.kechengid']  = array('eq', input('get.kechengid'));

        $result =  Db::name('input_result')
            ->alias('a')
            // ->join("kecheng b", 'a.kechengid = b.id')
            // ->join("teacher_info c", 'a.teacherid = c.teacherid')
            ->join("students d", 'a.studentid = d.id')

            ->field("a.*,d.studentname,d.student_no")
            ->where($map)->order('id')->select();
        // echo Db::name('task')->getLastSql();
        return json($result);
    }

    public function result_input_add()
    {
        $map['classid'] = array('eq', input('get.banjiid'));

        $kechengListData =  Db::name('kecheng')
            ->field('coursename, id')
            ->where('id', input('get.kechengid'))->select();
        $this->assign('kechengdata', $kechengListData);

        $student = Db::name('students')->where($map)->select();
        $this->assign('studentsData', $student);

        if (request()->isPost()) {
            $data = input('post.');
            $result =  Db::name('input_result')->insert($data);

            if ($result !== false) {
                $this->success('录入成功！', 'score/result_input');
            } else {
                $this->error($result);
            }
        }


        $this->assign('name', 'thinkphp');
        return $this->fetch();
    }

    // 编辑视图
    public function result_input_edit()
    {
        $map['classid'] = array('eq', input('get.banjiid'));

        $kechengListData =  Db::name('kecheng')
            ->field('coursename, id')
            ->where('id', input('get.kechengid'))->select();
        $this->assign('kechengdata', $kechengListData);

        $student = Db::name('students')->where($map)->select();
        $this->assign('studentsData', $student);
        return $this->fetch();
    }

    // 录入成绩编辑
    public function result_input_modify()
    {
        if (Request::instance()->isGet()) {
            $result =  Db::name('input_result')
                ->alias('a')
                ->join("students d", 'a.studentid = d.id')
                ->field("a.*,d.studentname,d.student_no")
                ->find(input('get.id'));
            if ($result !== false) {
                $this->success('成功！', '', $result);
            } else {
                $this->error($result);
            }
        }

        if (Request::instance()->isPost()) {
            $data = input('post.');
            $result = Db::name('input_result')
                ->where('id', $data['id'])
                ->update([
                    'studentid' => $data['studentid'],
                    'usual_score' => $data['usual_score'],
                    'test_score' => $data['test_score'],
                    'practice_score' => $data['practice_score'],
                    'total_score' => $data['total_score'],
                    'create_time' => date('y-m-d', time()),
                    // 'memo' => $data['memo'],
                    'check1' => 0,
                    'check2' => 0,

                ]);

            if ($result !== false) {
                $this->success('编辑成功！', 'score/result_input');
            } else {
                $this->error($result);
            }
        }
        return view();
    }

    public function result_check()
    {
        $data = input('post.');
        if (session('userclass') == 1) { // 二级学院审核
            $map = ['check1' =>  $data['check'],'nopass_reason1' =>  $data['nopass_reason']];
        } else {
            $map = ['check2' =>  $data['check'],'nopass_reason1' =>  $data['nopass_reason']];
        }

        // $params['a.banjiid'] = array('eq',$data['banjiid']);
        // $params['a.kechengid'] = array('eq',$data['kechengid']);

        // $where
        $result = Db::name('course_check')
            // ->alias('a')
            // ->join("course_check b", 'a.id = b.check_course_id')
            ->where('check_course_id', $data['id'])
            ->update($map);

        if ($result !== false) {
            $this->success('操作成功', 'score/scorecheck');
        } else {
            $this->error($result);
        }
    }

    // 删除操作
    public function result_input_remove()
    {
        $res = tableRemove('input_result');
        if ($res) {
            $this->success('删除成功！');
        } else {
            $this->error('删除失败');
        }
    }

    // 公布成绩
    public function public_result()
    {
        $kechengListData =  Db::name('kecheng')
            ->where('schoolid', 99)->select();
        $this->assign('kechengdata', $kechengListData);

        $teacherInfoListData =  Db::name('teacher_info')->select();
        $this->assign('teacherinfodata', $teacherInfoListData);

        $student = Db::name('students')->where('schoolid', 99)->select();
        $this->assign('studentsData', $student);

        return view();
    }

    public function get_pass_score()
    {
        // 审核通过更新数据库
        $isPass = Db::name('modify')->where('check1&check2', '=', 1)->select();
        if ($isPass) {
            foreach ($isPass as $item) {
                Db::name('input_result')
                    ->where('id', $item['scoreid'])
                    ->update(['total_score' => $item['newscore']]);
            }
        }

        // 搜索操作
        input('get.term') && $map['a.term'] = array('eq', input('get.term'));
        input('get.coursename') && $map['b.coursename'] = array('like', '%' . input('get.coursename') . '%');;
        input('get.name') && $map['d.studentname'] = array('like', '%' . input('get.name') . '%');;

        $map['a.schoolid'] = array('eq', 99);

        if (session("userclass") == 4) {
            // $map['b.college'] = array('ELT', 1);
            $map['a.studentid'] = array('eq', 4);  // 只显示登录同学的
        }

        $offset =  (input('get.page') - 1) * input('get.limit');
        $result =  Db::name('input_result')
            ->alias('a')
            ->join("kecheng b", 'a.kechengid = b.id')
            ->join("teacher_info c", 'a.teacherid = c.teacherid')
            ->join("students d", 'a.studentid = d.id')
            ->field("a.*, b.coursename,c.teachername,d.studentname")
            ->where($map)->order('id')->limit($offset, input('get.limit'))->select();

        $total =  Db::name('input_result')->alias('a')
            ->join("kecheng b", 'a.kechengid = b.id')
            ->join("teacher_info c", 'a.teacherid = c.teacherid')
            ->join("students d", 'a.studentid = d.id')
            ->field("a.*, b.coursename,c.teachername,d.studentname")->where($map)->order('id')->select();
        $listData['record'] = $result;
        $listData['total'] = count($total);

        return json($listData);
    }

    public function public_result_apply()
    {
        if (Request::instance()->isGet()) {
            $result =  Db::name('input_result')
                ->alias('a')
                // ->join("students d", 'a.studentid = d.id')
                ->field('a.total_score as oldscore,a.id as scoreid, a.*')
                ->find(input('get.id'));
            if ($result !== false) {
                $this->success('成功！', '', $result);
            } else {
                $this->error($result);
            }
        }

        if (Request::instance()->isPost()) {
            $data = input('post.');
            $result =  Db::name('modify')->insert($data);
            if ($result !== false) {
                $this->success('申请提交成功！', 'score/public_result');
            } else {
                $this->error($result);
            }
        }
    }

    /* 课程管理 */
    public function course_manage()
    {
        $kechengListData =  Db::name('kecheng')
            ->where('schoolid', 99)->select();
        $this->assign('kechengdata', $kechengListData);

        $teacherInfoListData =  Db::name('teacher_info')->select();
        $this->assign('teacherinfodata', $teacherInfoListData);
        return view();
    }

    public function course_add()
    {
        if (request()->isAjax()) {
            $data = input('post.');

            // $validate = new TestValidate;

            // if (!$validate->scene('taskadd')->check($data)) {
            //     return $validate->getError();
            // }

            $result =  Db::name('kecheng')->insert($data);

            if ($result !== false) {
                $this->success('添加成功！', 'score/course_manage');
            } else {
                $this->error($result);
            }
        }
        return view();
    }

    public function manage_course()
    {
        if (request()->isAjax()) {
            $data = input('post.');
            $result =  Db::table('courses_result')->insert($data);

            if ($result !== false) {
                $this->success('添加成功！', 'score/course_manage');
            } else {
                $this->error($result);
            }
        }
        return view();
    }

    public function manage_course_edit()
    {
        if (Request::instance()->isGet()) {
            $result =  Db::table('courses_result')
                // ->alias('a')
                // ->join("students d", 'a.studentid = d.id')
                ->find(input('get.id'));
            if ($result !== false) {
                $this->success('成功！', '', $result);
            } else {
                $this->error($result);
            }
        }

        if (Request::instance()->isPost()) {
            $data = input('post.');
            $result = Db::table('courses_result')
                ->where('id', $data['id'])
                ->update([
                    'teacherid' => $data['teacherid'],
                    'term' => $data['term'],
                    'kechengid' => $data['kechengid'],
                    'memo' => $data['memo'],
                    'score' => $data['score'],
                    'studentid' => $data['studentid'],
                    'result' => $data['result'],
                ]);

            if ($result !== false) {
                $this->success('编辑成功！', 'score/course_manage');
            } else {
                $this->error($result);
            }
        }
        return view();
    }

    public function course_remove()
    {
        if (Request::instance()->isGet()) {
            $res =  Db::table('courses_result')->where('id', input('get.id'))
                ->delete();
        } else {
            $ids = input('post.ids');
            $res = Db::table('courses_result')->delete($ids);
        }
        if ($res) {
            $this->success('删除成功！', 'score/course_manage');
        } else {
            $this->error('删除失败');
        }
    }

    public function get_course_list()
    {
        input('get.term') && $map['a.term'] = array('eq', input('get.term'));
        input('get.college') && $map['d.college'] = array('eq', input('get.college'));
        input('get.input_state') && $map['a.input_state'] = array('eq', input('get.input_state'));

        $map['a.schoolid'] = array('eq', 99);
        if (session('userclass') == 3) { // 教师登录 测试用，假设登录老师是 詹三
            $map['c.id']  = array('eq', 3);
        } else if (session('userclass') == 1) { // 学院登录
            // 返回该学院所有班级教程
            $map['d.college']  = array('eq', 1); // 1为计算机学院
        }

        $listData =  Db::table('courses_result')
            ->alias('a')
            ->join("kecheng b", 'a.kechengid = b.id')
            ->join("teacher_info c", 'a.teacherid = c.teacherid')
            ->join("class d", 'a.banjiid = d.id')
            ->join("course_check e", 'a.id = e.check_course_id')
            ->field("a.*,c.teachername,b.coursename,d.class_name, d.number, e.check1, e.check2, e.nopass_reason1, e.nopass_reason2")
            ->where($map)->order('a.id')->select();

        // 返回詹三老师教的所有课程
        return json($listData);
    }

    /* 成绩修改审批表 */
    public function scoreModify()
    {
        $kechengListData =  Db::name('kecheng')
            ->where('schoolid', 99)->select();
        $this->assign('kechengdata', $kechengListData);

        $teacherInfoListData =  Db::name('teacher_info')->select();
        $this->assign('teacherinfodata', $teacherInfoListData);

        $student = Db::name('students')->where('schoolid', 99)->select();
        $this->assign('studentsData', $student);

        return view();
    }

    public function get_modify_list()
    {
        $map['a.schoolid'] = array('eq', 99);
        $variable = session('userclass');
        if ($variable == 1 || $variable == 2) {
            $map['a.check3'] = array('eq', 1);
        }
        // input('get.id') && $map['a.id']  = array('eq', input('get.id'));
        // input('get.name') && $map['c.name']  = array('like', '%' . input('get.name') . '%');
        // input('get.teachername') && $map['b.teachername']  = array('like', '%' . input('get.teachername') . '%');
        // input('get.role') && $map['a.role']  = array('eq', input('get.role'));
        // input('get.create_time') && $map['a.create_time']  = array('like', '%' . input('get.create_time') . '%');

        $listData =  Db::name('modify')
            ->alias('a')
            // ->join("kecheng b", 'a.kechengid = b.kechengid')
            ->join("teacher_info c", 'a.teacherid = c.teacherid')
            ->join("students d", 'a.studentid = d.id')
            ->field("a.*,c.teachername,d.studentname")
            ->where($map)->order('a.id')->select();
        return json($listData);
    }

    // 成绩修改审核
    public function modify_check()
    {
        if (Request::instance()->isGet()) {
            $result =  Db::name('modify')
                // ->alias('a')
                // ->join("students d", 'a.studentid = d.id')
                // ->field('a.score as oldscore,a.id as scoreid, a.*')
                ->find(input('get.id'));
            if ($result !== false) {
                $this->success('成功！', '', $result);
            } else {
                $this->error($result);
            }
        }

        if (Request::instance()->isPost()) {
            $data = input('post.');

            $variable = session('userclass');
            switch ($variable) {
                case '0': // 管理员
                    # code...
                    break;
                case '1': // 学院
                    $map = ['check1' =>  $data['check']];

                    break;
                case '2': // 教务处
                    $map = ['check2' =>  $data['check']];

                    break;
                case '3': // 教师
                    $map = [
                        'check3' =>  $data['check'],
                        'newscore' =>  $data['newscore'],
                        'change_reason' =>  $data['change_reason'],
                        'verify_file' =>  $data['verify_file'],
                    ];
                    break;
            }

            $result = Db::name('modify')
                ->where('id', $data['id'])
                ->update($map);

            if ($result !== false) {
                $this->success('审核成功', 'score/scoreModify');
            } else {
                $this->error($result);
            }
        }
    }

    public function modify_remove()
    {
        $res = tableRemove('modify');
        if ($res) {
            $this->success('删除成功！', 'score/scoreModify');
        } else {
            $this->error('删除失败');
        }
    }

    public function verify_file_upload()
    {
        $file = request()->file('file'); // 获取上传的文件
        if ($file == null) {
            exit(json_encode(array('code' => 1, 'msg' => '未上传图片')));
        }

        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads', true, false); // 移动文件到指定目录 没有则创建
        $img = '/uploads/' . $info->getSaveName();
        exit(json_encode(array('code' => 0, 'msg' => $img)));
    }


    // 成绩审核
    function scoreCheck()
    {
        $kechengListData =  Db::name('kecheng')
            ->where('schoolid', 99)->select();
        $this->assign('kechengdata', $kechengListData);

        $teacherInfoListData =  Db::name('teacher_info')->select();
        $this->assign('teacherinfodata', $teacherInfoListData);

        $student = Db::name('students')->where('schoolid', 99)->select();
        $this->assign('studentsData', $student);

        $college = Db::name('college')->select();
        $this->assign('college', $college);

        return view();
    }

    // 成绩审核统计页面number
    public function scoreStatsCheck()
    {
        $data = input('get.');
        $map['a.kechengid'] = array('eq', input('get.kechengid'));

        if (session("userclass") == 1) {
            $map['b.college'] = array('eq', 1);
        }
        $currentClass =  Db::name('class')
            ->where('id', $data['banjiid'])->find();
        $this->assign('nowClass', $currentClass);

        $kechengListData =  Db::name('kecheng')
            ->where('id', $data['kechengid'])->find();
        $this->assign('kechengdata', $kechengListData);


        $classData =  Db::table('courses_result')
            ->alias('a')
            ->join("class b", 'a.banjiid = b.id')
            ->field("a.*,b.class_name, b.number")
            ->where($map)->select();
        $this->assign('classData', $classData);
        return $this->fetch();
    }

    // 获取成绩录入状态
    public function getRecordEntrySituation()
    {
        $map['a.schoolid'] = array('eq', 99);
        $map['a.term'] = array('eq', 1);

        if (session("userclass") == 1) {
            $map['b.college'] = array('ELT', 1);
        }

        $allCourse = Db::table('courses_result')
            ->alias('a')
            ->join("kecheng b", 'a.kechengid = b.id')
            ->join("college c", 'b.college = c.id')
            ->field("a.*")
            ->where($map)->select();

        $allClass = Db::table('courses_result')
            ->alias('a')
            ->join("class b", 'a.banjiid = b.id')
            ->join("college c", 'b.college = c.id')
            ->field("a.*")
            ->where($map)->select();

        $map['a.input_state'] = array('eq', 1);
        $courseInputNum =  Db::table('courses_result')
            ->alias('a')
            ->join("kecheng b", 'a.kechengid = b.id')
            ->join("college c", 'b.college = c.id')
            ->field("a.*")
            ->where($map)->order('a.id')->select();

        $classInputNum =  Db::table('courses_result')
            ->alias('a')
            ->join("class b", 'a.banjiid = b.id')
            ->join("college c", 'b.college = c.id')
            ->field("a.*")
            ->where($map)->order('a.id')->select();

        $jsonData['courseInputNum'] = count($courseInputNum);
        $jsonData['allCourse'] = count($allCourse);
        $jsonData['classInputNum'] = count($classInputNum);
        $jsonData['allClass'] = count($allClass);

        return json($jsonData);
    }

    // 记录录入状态
    public function finishInput()
    {
        $map['schoolid'] = array('eq', 99);
        $map['kechengid'] = array('eq', input('post.kechengid'));
        $map['banjiid'] = array('eq', input('post.banjiid'));

        $result =  Db::table('courses_result')
            ->where($map)->update(['input_state' => input('post.input_state')]);

        if ($result !== false) {
            $this->success('操作成功', '');
        } else {
            $this->error($result);
        }
    }
}
